package com.example.demo.service.impl;

import com.example.demo.common.ErrorCode;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.MyUserMapper;
import com.example.demo.mapper.TeamMapper;
import com.example.demo.myModel.entity.MyUser;
import com.example.demo.myModel.entity.Team;
import com.example.demo.service.TeamService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class TeamServiceImpl implements TeamService {

    @Resource
    private TeamMapper teamMapper;
    
    @Resource
    private MyUserMapper myUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Team createTeam(String teamName, Long leaderId) {
        // 验证队长是否存在
        MyUser leader = myUserMapper.selectById(leaderId);
        if (leader == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队长不存在");
        }
        
        // 创建团队
        Team team = new Team();
        team.setTeamName(teamName);
        team.setID(Math.toIntExact(leaderId));
        
        teamMapper.insert(team);
        return team;
    }

    @Override
    public boolean verifyStudent(Long studentId) {
        MyUser student = myUserMapper.selectById(studentId);
        return student != null && student.getStatus() == 1;
    }

    @Override
    public void addTeamMember(Integer teamId, Long studentId) {
        // 验证学生是否存在
        if (!verifyStudent(studentId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "学生不存在或已被禁用");
        }
        
        // TODO: 可以添加团队成员表来支持多对多关系
    }
} 